package pl.edu.agh.uhm.upnp.discoverer;

import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.osgi.framework.ServiceReference;
import org.osgi.service.upnp.UPnPDevice;
import org.osgi.util.tracker.ServiceTracker;

import pl.edu.agh.uhm.discoverer.Hypervisor;
import pl.edu.agh.uhm.discoverer.VirtualMachine;

public class UPnPBasedHypervisor implements Hypervisor {

	
	ServiceTracker serviceTracker;
	private final String id; 
	
	public UPnPBasedHypervisor(ServiceReference device) {
	
		Object udn= device.getProperty(UPnPDevice.UDN);
		if(udn!=null)
			id=(String)udn;
		else
			id="UNKNOWN";
		serviceTracker=new ServiceTracker(Activator.context,device, null);
		serviceTracker.open();
		
	}
	
	@Override
	public void start() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void stop() {
		// TODO Auto-generated method stub
		
	}
	
	public String toString(){
		StringBuilder sb=new StringBuilder();
		sb.append("---UPnP Based Hypervisor---\n");
		UPnPDevice upnpDevice=(UPnPDevice)serviceTracker.getService();
		if(upnpDevice==null)
			sb.append("Cannot found related UPnP device");
		else{
			Dictionary dict=upnpDevice.getDescriptions(null);
			Enumeration keys=dict.keys();
			while(keys.hasMoreElements()){
				String key=(String)keys.nextElement();
				sb.append(key);
				sb.append("=");
				sb.append(dict.get(key));
				sb.append("\n");
			}			
		}
		return sb.toString();
		
	}

	@Override
	public Set<String> getVirtualMachineIDs() {
		UPnPDevice upnpDevice=(UPnPDevice)serviceTracker.getService();
		if(upnpDevice==null)
			return null;
		else{
			Dictionary dict=upnpDevice.getDescriptions(null);
			if(dict.get(UPnPDevice.CHILDREN_UDN)!=null){
				String[] childrenUDN=(String[])dict.get(UPnPDevice.CHILDREN_UDN);
				Set<String> result=new HashSet<String>();
				for(String ch:childrenUDN){
					result.add(ch);
				}
				return result;
			}
			else 
				return null;
		}
	}

	public String getId() {
		return id;
	}
	

}
